//
//  ZPAdvertiseView.m
//  ZPIOSEducation
//
//  Created by mini1 on 2016/11/24.
//  Copyright © 2016年 mini1. All rights reserved.
//

#import "ZPAdvertiseView.h"

#define zPushBtnDiameter 60

@interface ZPAdvertiseView ()

@property (nonatomic, strong) UIImageView *advertiseView;

@property (nonatomic, strong) UIButton *countBtn;

@property (nonatomic, strong) NSTimer *countTimer;

@property (nonatomic, assign) int count;

@end

@implementation ZPAdvertiseView

/** 广告图片显示时间 */
static int const showTime = 4;

/** 懒加载 */
- (NSTimer *)countTimer {
    if (_countTimer == nil) {
        _countTimer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
    }
    return _countTimer;
}

/** 初始化 */
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        // 视图上设置广告图片
        _advertiseView = [[UIImageView alloc] initWithFrame:frame];
//        _advertiseView.image = [UIImage imageNamed:@"2"];
        _advertiseView.userInteractionEnabled = YES;
        _advertiseView.clipsToBounds = YES;
        _advertiseView.contentMode = UIViewContentModeScaleAspectFill;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushInterface)];
        [_advertiseView addGestureRecognizer:tap];
        
        // 跳过按钮
        _countBtn = [[UIButton alloc] initWithFrame:CGRectMake(Main_Screen_Width-zPushBtnDiameter-30, 30, zPushBtnDiameter, zPushBtnDiameter)];
        
        [[ZPShareView sharedSingleView] setupButton:_countBtn backgroundColor:zFreeColor(194, 195, 197, 0.5) image:nil title:@"跳过" titltColor:white_color titleFont:15.0];
        
        [_countBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
        ViewBorderRadius(_countBtn, _countBtn.xj_width * 0.5, 5.0, zFreeColor(101, 104, 108, 0.3));

        [self addSubview:_advertiseView];
        [self addSubview:_countBtn];
    }
    return self;
}

/** 倒计时 */
- (void)countDown {
    _count --;
    [_countBtn setTitle:[NSString stringWithFormat:@"%dS跳过",_count] forState:UIControlStateNormal];
    if (_count == 0) {
        [self dismiss];
    }
}

- (void)pushInterface {
    [self dismiss];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"pushAdvertiseInterface" object:nil userInfo:nil];
}

-(void)setFilePath:(NSString *)filePath {
    _filePath = filePath;
    _advertiseView.image = [UIImage imageWithContentsOfFile:filePath];
}


/** 在window展示当前界面 */
- (void)showAdvertiseView {
     [self startCountdownGCD]; // 倒计时方法1:GCD
    
   // [self startCountdownTimer];  // 倒计时方法2:计时器
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow; // window添加本视图
    [window addSubview:self];
}



/** timer倒计时 */
- (void)startCountdownTimer {
    _count = showTime;
    [[NSRunLoop currentRunLoop] addTimer:self.countTimer forMode:NSRunLoopCommonModes];
}



/** GCD倒计时 */
- (void)startCountdownGCD {
    __block int timeout = showTime + 1; //倒计时时间 + 1
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0 * NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self dismiss];
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [_countBtn setTitle:[NSString stringWithFormat:@"跳过%d",timeout] forState:UIControlStateNormal];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}


/** 移除广告页面 */
- (void)dismiss {
    [self.countTimer invalidate];
    self.countTimer = nil;
    [UIView animateWithDuration:1.0 animations:^{
               self.alpha = 0.f;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

@end
